package com.meirengu.channel.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.meirengu.channel.service.WeidaiService;
import com.meirengu.utils.HttpUtil;
import com.meirengu.webview.common.Constants;
import com.meirengu.webview.model.KwWeidaiPush;
import com.meirengu.webview.model.KwWeidaiPushLog;
import com.meirengu.webview.service.KwWeidaiPushLogService;
import com.meirengu.webview.service.KwWeidaiPushService;
import com.meirengu.webview.utils.ConfigUtil;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 微贷
 *
 * @author Mao
 * @create 2017-12-15 12:11
 */
@Service
public class WeidaiServiceImpl implements WeidaiService {

    Logger logger = LoggerFactory.getLogger(WeidaiServiceImpl.class);
    @Autowired
    private KwWeidaiPushService kwWeidaiPushService;
    @Autowired
    private KwWeidaiPushLogService kwWeidaiPushLogService;


    /*
     *获取token
     */
    public JSONObject accessToken(String mobile) throws Exception {

        String domain = ConfigUtil.getConfig("weidai.domain");
        String url = domain + "/partner/login";

        String userName = ConfigUtil.getConfig("weidai.username");
        String password = ConfigUtil.getConfig("weidai.password");

        Map<String, String> params = new HashMap<>();
        params.put("userName", userName);
        params.put("password", password);

        //接口调用信息表
        KwWeidaiPush kwWeidaiPush = new KwWeidaiPush();
        kwWeidaiPush.setInterfaceCode("weidai-token");
        kwWeidaiPush.setInterfaceName("微贷获取token");
        kwWeidaiPush.setMobile(mobile);
        kwWeidaiPush.setCode(Constants.BUSINESS_STATUS_FAIL);


        KwWeidaiPushLog kwWeidaiPushLog = new KwWeidaiPushLog();
        kwWeidaiPushLog.setInterfaceCode("weidai-token");
        kwWeidaiPushLog.setInterfaceName("微贷获取token");
        kwWeidaiPushLog.setMobile(mobile);
        kwWeidaiPushLog.setSendUrl(url.toString());
        kwWeidaiPushLog.setParams(params.toString());

        HttpUtil.HttpResult hr = null;
        JSONObject item = new JSONObject();
        try {
            hr = HttpUtil.doPostForm(url, params);
            int code = hr.getStatusCode();
            if (code == 200) {
                kwWeidaiPushLog.setBackUrl(hr.toString());
                kwWeidaiPushLog.setHttpCode(200);
                kwWeidaiPushLog.setHttpContent(hr.toString());

                logger.info("==WeidaiServiceImpl.accessToken request success. result:{}", hr.toString());
                String content = hr.getContent();
                JSONObject returnMsg = JSONObject.parseObject(content);
                Integer rCode = returnMsg.getInteger("code");
                boolean success = returnMsg.getBoolean("success");
                String rMsg = returnMsg.getString("message");
                List dataModel = returnMsg.getJSONArray("dataModel");
                if (rCode.intValue() == 1000 && success) {
                    item = returnMsg.getJSONObject("item");
                    kwWeidaiPush.setCode(Constants.BUSINESS_STATUS_SUCCESS);
                    kwWeidaiPush.setMessage("成功");
                    logger.info("==WeidaiServiceImpl.accessToken business success");
                } else {
                    kwWeidaiPush.setCode(Constants.BUSINESS_STATUS_OTHER);
                    kwWeidaiPush.setMessage("rCode: " + rCode + " rMsg:" + rMsg);
                    logger.warn("==WeidaiServiceImpl.accessToken business fail");
                }
            } else {
                kwWeidaiPushLog.setBackUrl(hr.toString());
                kwWeidaiPushLog.setHttpCode(code);
                kwWeidaiPushLog.setHttpContent(hr.toString());
                logger.warn("==WeidaiServiceImpl.accessToken request fail. code:{}, result:{}", code, hr.toString());
            }
        } catch (Exception e) {
            kwWeidaiPushLog.setHttpCode(408);
            kwWeidaiPushLog.setHttpContent("Exception");
            e.printStackTrace();
            logger.error(ExceptionUtils.getFullStackTrace(e));
        } finally {
            kwWeidaiPushService.insert(kwWeidaiPush);
            kwWeidaiPushLog.setPushId(kwWeidaiPush.getId());
            kwWeidaiPushLogService.insert(kwWeidaiPushLog);
            return item;
        }
    }


    /**
     * @param
     * @return
     */

    public Integer applyLoan(String name, String mobile, String sex, String city) throws Exception {

        String domain = ConfigUtil.getConfig("weidai.domain");
        String url = domain + "/partner/sendPiece";

        JSONObject item = accessToken(mobile);
        if (item != null) {
            String token = item.getString("token");
            if (StringUtils.isNotBlank(token)) {
                JSONArray channels = item.getJSONArray("channels");
                for (int i = 0; i < channels.size(); i++) {
                    String channelCode = channels.getJSONObject(i).getString("channelCode");
                    String channel = channels.getJSONObject(i).getString("channel");
                    if (StringUtils.isNotBlank(channelCode) && StringUtils.isNotBlank(channel)) {
                        Map<String, String> params = new HashMap<>();
                        params.put("token", token);
                        params.put("borrowType", "0");
                        params.put("channelCode", channelCode);
                        params.put("channel", channel);
                        params.put("name", name);
                        params.put("mobile", mobile);
                        params.put("sex", sex);
                        params.put("city", city);


                        //接口调用信息表
                        KwWeidaiPush kwWeidaiPush = new KwWeidaiPush();
                        kwWeidaiPush.setInterfaceCode("weidai");
                        kwWeidaiPush.setInterfaceName("微贷");
                        kwWeidaiPush.setMobile(mobile);
                        kwWeidaiPush.setCode(Constants.BUSINESS_STATUS_FAIL);


                        KwWeidaiPushLog kwWeidaiPushLog = new KwWeidaiPushLog();
                        kwWeidaiPushLog.setInterfaceCode("weidai");
                        kwWeidaiPushLog.setInterfaceName("微贷");
                        kwWeidaiPushLog.setMobile(mobile);
                        kwWeidaiPushLog.setSendUrl(url.toString());
                        kwWeidaiPushLog.setParams(params.toString());


                        HttpUtil.HttpResult hr = null;
                        try {
                            hr = HttpUtil.doPostForm(url, params);
                            int code = hr.getStatusCode();
                            if (code == 200) {
                                kwWeidaiPushLog.setBackUrl(hr.toString());
                                kwWeidaiPushLog.setHttpCode(200);
                                kwWeidaiPushLog.setHttpContent(hr.toString());

                                logger.info("==WeidaiServiceImpl.applyLoan request success. result:{}", hr.toString());
                                String content = hr.getContent();
                                JSONObject returnMsg = JSONObject.parseObject(content);
                                Integer rCode = returnMsg.getInteger("code");
                                boolean success = returnMsg.getBoolean("success");
                                String rMsg = returnMsg.getString("message");
                                if (rCode.intValue() == 1000 && success) {
                                    kwWeidaiPush.setCode(Constants.BUSINESS_STATUS_SUCCESS);
                                    kwWeidaiPush.setMessage("成功");
                                    logger.info("==WeidaiServiceImpl.applyLoan business success");
                                } else {
                                    kwWeidaiPush.setCode(Constants.BUSINESS_STATUS_OTHER);
                                    kwWeidaiPush.setMessage("rCode: " + rCode + " rMsg:" + rMsg);
                                    logger.warn("==WeidaiServiceImpl.applyLoan business fail");
                                }
                            } else {
                                kwWeidaiPushLog.setBackUrl(hr.toString());
                                kwWeidaiPushLog.setHttpCode(code);
                                kwWeidaiPushLog.setHttpContent(hr.toString());
                                logger.warn("==WeidaiServiceImpl.applyLoan request fail. code:{}, result:{}", code, hr.toString());
                            }
                        } catch (Exception e) {
                            kwWeidaiPushLog.setHttpCode(408);
                            kwWeidaiPushLog.setHttpContent("Exception");
                            e.printStackTrace();
                            logger.error(ExceptionUtils.getFullStackTrace(e));
                        } finally {
                            kwWeidaiPushService.insert(kwWeidaiPush);
                            kwWeidaiPushLog.setPushId(kwWeidaiPush.getId());
                            kwWeidaiPushLogService.insert(kwWeidaiPushLog);
                            return kwWeidaiPush.getCode();
                        }
                    }
                }
            }
        }
        return 500;

    }


}
